package com.zx._02_thread.线程池;

import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SynchronousQueueDemo {

    private static final ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {
        SynchronousQueue<String> queue = new SynchronousQueue<String>();

        pool.execute(() -> {
            log.info("1. 没有消费者时，调用offer保存数据，res={}", queue.offer("A"));
        });

        Thread.sleep(500L);

        pool.execute(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    log.info("2. 开启一个消费者线程，阻塞式发现数据，i={}, data={}", i, queue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread.sleep(500L);

        pool.execute(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    log.info("3. 有消费者时，调用offer保存数据，res={}", queue.offer("B_" + i));
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        while (pool.getActiveCount() != 0 && !queue.isEmpty()) {
            Thread.sleep(1000L);
        }
        pool.shutdown();
    }
}
